package com.lad.pdfdemo.controller;

import com.lad.pdfdemo.component.JasperHelper;
import com.lad.pdfdemo.entity.User;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * springboot+ireport+jasperReports导出PDF图
 * https://www.jianshu.com/p/72de15a83e64
 */
@Controller
@RequestMapping(value = "/report")
public class ReportController {
    @RequestMapping(value = "/export/pdf2")
    public void downloadRequisitionPDF2(final ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //此处使用的pojo类必须和模板文件中的类一致,否则无法正确生成.
        List<User> userList = Arrays.asList(new User(12,"aa"),new User(12,"bb"));
        //模拟数据源
        JRDataSource jrDataSource = new JRBeanCollectionDataSource(userList);
        HashMap<String, Object> objectHashMap = new HashMap<>();
        //objectHashMap.put("id",12);
        //objectHashMap.put("name","张三");
        //此处demo直接使用的磁盘绝对路径了,实际生产老实取文件路径
        //File reporeFile = new File("templates/report1.jasper");
        //ClassPathResource reporeFile = new ClassPathResource("templates/report1.jasper");
        File reporeFile = ResourceUtils.getFile("D:\\Dev_Code\\idea-project\\pdfdemo\\src\\main\\resources\\templates\\report1.jasper");
        JasperHelper.showPdf("导出测试", reporeFile.getPath(), request, response, objectHashMap, jrDataSource);
    }
}